<template>
	<div class="madp-chanel-statistics">
		<div v-show="!detailShow">
			<!-- 成员信息 -->
			<div class="madp-back-title">
				<backTitle @goBack="goBack" title="成员详情" />
			</div>
			<div class="madp-employee-info-wrap" v-if="employeeInfo">
				<div class="madp-employee madp-employee-item">
					<div class="madp-employee-avatar-wrap">
						<img :src="employeeInfo.avatar" class="madp-employee-avatar" v-if="employeeInfo.avatar" />
						<span class="madp-employee-avatar" v-else>
							{{ employeeInfo.employeeName ? employeeInfo.employeeName.substr(employeeInfo.employeeName.length - 1, 1) : '' }}
						</span>
					</div>
					<div class="madp-employee-info">
						<div class="madp-employee-name">{{ employeeInfo.employeeName }}</div>
						<div class="madp-operation-tags">
							<!-- <div class="madp-operation-tag">管理员</div> -->
							<!-- 设置管理权限功能，暂时没有 -->
							<!-- <div class="madp-operation-tag">管理权限</div> -->
						</div>
					</div>
				</div>
				<div class="madp-top-statistics-box madp-employee-item">
					<div class="madp-statistics-item">
						<span class="madp-statistics-item-desc">客户总数</span>
						<span class="madp-statistics-item-number-wrap">
							<span class="madp-statistics-item-number">
								{{ employeeInfo.contactCounts }} </span
							>人
						</span>
					</div>
					<div class="madp-divider"></div>
					<div class="madp-statistics-item">
						<span class="madp-statistics-item-desc">昨日新增</span>
						<span class="madp-statistics-item-number-wrap">
							<span class="madp-statistics-item-number">
								{{ employeeInfo.contactAdd }} </span
							>人
						</span>
					</div>
				</div>
			</div>
			<!-- 联系客户统计 -->
			<basic-container>
				<div class="madp-statistics-data" v-if="employeeInfo">
					<div class="madp-statistics-title">
						<span>联系客户统计</span>
						<el-popover placement="bottom-start" width="500" trigger="hover">
							<div>
								<p>1、聊天总数:成员有主动发送过消息的单聊总数</p>
								<p>2、发送消息数:成员在单聊中发送的消息总数</p>
								<p>3、已回复聊天占比:客户主动发起聊天后，成员在一个自然日内有回复过消息的聊天数/客户主动发起的聊天比例</p>
								<p>4、平均首次回复时长:客户主动发起聊天后，成员在一个自然日内首次回复的时长间隔为首次回复时长</p>
							</div>
							<el-button type="text" slot="reference" style="margin-left: 20px">
								统计说明
								<i class="el-icon-question"></i>
							</el-button>
						</el-popover>
					</div>
					<statistics-card :cardInfo="cardInfo" :cardData="employeeInfo" />
				</div>
			</basic-container>
			<!-- 趋势图 -->
			<basic-container>
				<div class="madp-statistics-chart">
					<div class="madp-statistics-title">趋势图</div>
					<div class="madp-gap-wrap">
						<div class="madp-statistics-tabs">
							<div class="madp-statistics-tabs-left">
								<el-button-group>
									<el-button :type="type === item.value ? 'primary' : ''" v-for="item in statisticDimensionTypes" :key="item.value" @click="selectDimensionType(item)">{{
										item.label
									}}</el-button>
								</el-button-group>
							</div>
						</div>
						<div class="madp-date-picker-wrap madp-statistics-tabs">
							<div class="madp-statistics-tabs-left">
								<el-form :inline="true" class="madp-chart-form">
									<el-form-item>
										<el-select class="madp-date-select" v-model="tendencyDateType" placeholder="自定义" @change="changeTendencyDateType">
											<el-option v-for="item in dateTypes" :key="item.type" :label="item.label" :value="item.type"></el-option>
										</el-select>
									</el-form-item>
									<el-form-item label="自定义:">
										<el-date-picker
											v-model="tendencyDateRangeVal"
											type="daterange"
											range-separator="至"
											start-placeholder="开始日期"
											end-placeholder="结束日期"
											format="yyyy-MM-dd"
											value-format="yyyy-MM-dd"
											:picker-options="{
												disabledDate(time) {
													return time.getTime() > Date.now() - 8.64e7;
												},
											}"
											@change="changeTendencyDateRangeVal"
										></el-date-picker>
									</el-form-item>
								</el-form>
							</div>
							<el-button plain @click="resetDateType">重置</el-button>
						</div>
						<div class="madp-data-tip" v-if="tendencyDateType === 1">提示:此处的近一周的数据从昨日开始算起</div>
						<!-- 折线图 -->
						<div
							id="detailLineChart"
							style="
								width: 100%;
								height: 400px;
								margin: 30px auto;
							"
							v-show="lineChartOption.xAxis.data && lineChartOption.xAxis.data.length > 0"
						></div>
					</div>
					<div class="madp-horizontal-divider"></div>
					<div class="madp-gap-wrap">
						<div class="madp-statistics-table">
							<el-table
								:header-cell-style="{
									background: 'rgb(255, 191, 191)',
									color: 'rgb(44,44,44)',
								}"
								stripe
								:data="dateTableData"
								@sort-change="sortDateTableData"
							>
								<el-table-column prop="synTime" label="日期" sortable="custom" align="center"></el-table-column>
								<el-table-column prop="chatCnts" label="聊天总数" width="200" sortable="custom" align="center"></el-table-column>
								<el-table-column prop="messageCnts" label="发送消息数" sortable="custom" align="center"></el-table-column>
								<el-table-column label="已回复聊天占比" prop="replyPercentages" sortable="custom" align="center">
									<template slot-scope="scope"
										>{{ scope.row.replyPercentages }}%</template
									>
								</el-table-column>
								<el-table-column label="平均回复时长" prop="avgReplyTimes" sortable="custom" align="center">
									<template slot-scope="scope"
										>{{ scope.row.avgReplyTimes }}分钟</template
									>
								</el-table-column>
							</el-table>
							<!-- 列表分页 -->
							<el-pagination
								background
								v-if="datePagination.total > 0"
								class="madp-black-pagination"
								@size-change="handleSizeChangeByDate"
								@current-change="handleCurrentChangeByDate"
								:current-page="datePagination.current"
								:page-sizes="[10, 20, 30, 50, 100]"
								:page-size="datePagination.size"
								layout="total, sizes, prev, pager, next, jumper"
								:total="datePagination.total"
							></el-pagination>
						</div>
					</div>
				</div>
			</basic-container>
			<!-- 客户列表 -->
			<basic-container>
				<div class="madp-statistics-chart">
					<div class="madp-statistics-title">客户列表</div>
					<div class="madp-customer-total">共{{ customerTableData.length }}个客户</div>
					<div class="madp-gap-wrap">
						<div class="madp-statistics-table">
							<el-table
								:header-cell-style="{
									background: 'rgb(255, 191, 191)',
									color: 'rgb(44,44,44)',
								}"
								stripe
								:data="customerTableData"
							>
								<el-table-column label="全部客户">
									<template slot-scope="scope">
										<div v-if="scope.row" class="madp-table-user-wrap">
											<img :src="scope.row.avatar" class="madp-table-avatar" v-if="scope.row.avatar" />
											<span class="madp-table-avatar" v-else>
												{{ scope.row.name ? scope.row.name.substr(scope.row.name.length - 1, 1) : '' }}
											</span>
											<span>{{ scope.row.name }}</span>
										</div>
									</template>
								</el-table-column>
								<el-table-column prop="chat_cnt" label="客户评分" width="200" align="center">
									<template>{{ '-' }}</template>
								</el-table-column>
								<el-table-column prop="message_cnt" label="客户积分" align="center">
									<template>{{ '-' }}</template>
								</el-table-column>
								<el-table-column label="标签" align="center">
									<template slot-scope="scope">{{ scope.row.tags.join('，') }}</template>
								</el-table-column>
								<el-table-column label="添加时间" align="center">
									<template slot-scope="scope">{{ scope.row.createTime }}</template>
								</el-table-column>
								<el-table-column label="上次对话时间" align="center">
									<template>{{ '-' }}</template>
								</el-table-column>
								<el-table-column label="添加渠道" align="center">
									<template slot-scope="scope">{{ scope.row.addWayText || '-' }}</template>
								</el-table-column>
								<el-table-column label="操作" align="center">
									<template slot-scope="scope">
										<el-button type="text" disabled>聊天记录</el-button>
										<el-button type="text" @click="showDetail(scope.row.contactId)">详情</el-button>
									</template>
								</el-table-column>
							</el-table>
						</div>
					</div>
				</div>
			</basic-container>
		</div>

		<customer-detail v-if="detailShow" :detailMsg="detailMsg" @goBack="setDetailShow"></customer-detail>
	</div>
</template>
<script>
import { employeeInfo, tendencyData, tableDataByDate, customerData } from '@/api/operation-manage/employee-statistics';
import customerDetail from '@/views/customer/customer-list/detail';
import BackTitle from '@/components/back-title/';
import StatisticsCard from '@/components/statistics-card/';
export default {
	components: {
		customerDetail,
		BackTitle,
		StatisticsCard,
	},
	props: {
		queryData: {
			type: Object,
			default: () => {
				return {};
			},
		},
	},
	data() {
		return {
			detailShow: false,
			detailMsg: {},
			employeeId: '',
			employeeInfo: {},
			type: 1, //维度 聊天总数、发送消息数、已回复聊天占比、平均首次回复时长
			typeName: '聊天总数',
			statisticDimensionTypes: [
				{
					label: '聊天总数',
					value: 1,
				},
				{
					label: '发送消息数',
					value: 2,
				},
				{
					label: '已回复聊天占比',
					value: 3,
				},
				{
					label: '平均首次回复时长',
					value: 4,
				},
			],
			// 趋势图相关
			tendencyDateType: '', //日期选择
			dateTypes: [
				{
					type: 0,
					label: '昨日',
				},
				{
					type: 1,
					label: '近一周',
				},
				{
					type: 2,
					label: '近一个月',
				},
			],
			tendencyDateRangeVal: ['2021-05-18', '2021-05-18'],
			tendencyForm: {
				startTime: '',
				endTime: '',
			},
			dateTableData: [],
			datePagination: {
				current: 1,
				size: 10,
			},
			//折线图数据
			lineChartOption: {
				tooltip: {
					trigger: 'axis',
					axisPointer: {
						// 坐标轴指示器，坐标轴触发有效
						type: 'line', // 默认为直线，可选为:'line' | 'shadow'
					},
					formatter: '{b}<br>聊天总数: {c}条',
				},
				xAxis: {
					type: 'category',
					data: [],
				},
				yAxis: {
					name: '条',
					type: 'value',
				},
				series: [
					{
						name: '聊天总数',
						type: 'line',
						data: [],
						lineStyle: {
							color: '#ED5555',
						},
						itemStyle: {
							color: '#ED5555',
						},
					},
				],
			},
			lineChartData: [],
			// 客户列表
			customerTableData: [],
			cardInfo: [
				{
					label: '聊天总数(条)',
					key: 'chatCnts',
					color: '#FFD700',
				},
				{
					label: '发送消息数(条)',
					key: 'messageCnts',
					color: '#FF8C00',
				},
				{
					label: '已回复聊天占比',
					key: 'replyPercentages',
					color: '#90EE90',
				},
				{
					label: '昨日平均首次回复时长(分)',
					key: 'avgReplyTimes',
					color: '#00CED1',
				},
			],
		};
	},
	created() {
		this.employeeId = this.queryData.employeeId;
		// 获取成员基本信息
		this.fetchEmployeeInfo();
		this.fetchCustomerData();
		this.tendencyDateType = 1;
		// this.changeTendencyDateType(this.tendencyDateType);
	},
	mounted() {
		this.$nextTick(() => {
			this.changeTendencyDateType(this.tendencyDateType);
		});
	},
	methods: {
		goBack() {
			this.$emit('close');
		},
		// 时间戳转日期
		formatDate(val) {
			let time = new Date(val * 1000);
			let y = time.getUTCFullYear();
			let m = time.getMonth() + 1 < 10 ? '0' + (time.getMonth() + 1) : time.getMonth() + 1;
			let d = time.getDate() < 10 ? '0' + time.getDate() : time.getDate();

			return y + '-' + m + '-' + d;
		},

		// 获取成员基本信息
		fetchEmployeeInfo() {
			employeeInfo({ employeeId: this.employeeId }).then((res) => {
				if (res.data && res.data.code === 0) {
					this.employeeInfo = res.data.data;
				}
			});
		},
		resetDateType() {
			this.tendencyDateType = 1;
			this.changeTendencyDateType(this.tendencyDateType);
		},
		// 切换趋势图数据参数
		selectDimensionType(item) {
			this.typeName = item.label;
			this.type = item.value;
			// 调查询接口
			let obj = {
				startTime: this.tendencyForm.startTime,
				endTime: this.tendencyForm.endTime,
				type: this.type,
				employeeId: this.employeeId,
			};
			this.fetchTendencyData(obj);
		},
		changeTendencyDateType(val) {
			let endTime = new Date();
			let startTime = new Date();
			endTime.setTime(endTime.getTime() - 3600 * 1000 * 24);
			if (val === 0) {
				startTime = endTime;
			} else if (val === 1) {
				startTime.setTime(startTime.getTime() - 3600 * 1000 * 24 * 7);
			} else {
				startTime.setTime(startTime.getTime() - 3600 * 1000 * 24 * 30);
			}
			this.tendencyDateRangeVal = [startTime, endTime];
			startTime = this.formatDate(startTime.getTime() / 1000);
			endTime = this.formatDate(endTime.getTime() / 1000);
			this.tendencyForm.startTime = startTime;
			this.tendencyForm.endTime = endTime;
			let obj = {
				startTime,
				endTime,
			};
			this.fetchTendencyData(
				Object.assign(
					{
						employeeId: this.employeeId,
						type: this.type,
					},
					obj,
				),
			);
			this.fetchTableDataByDate(Object.assign({ employeeId: this.employeeId }, obj));
		},
		changeTendencyDateRangeVal(val) {
			let startTime = '',
				endTime = '';
			if (!val) {
				this.tendencyDateType = '';
			} else {
				startTime = val[0];
				endTime = val[1];
				this.tendencyDateType = '';
				this.tendencyForm.startTime = startTime;
				this.tendencyForm.endTime = endTime;
				let obj = {
					startTime,
					endTime,
				};
				this.fetchTendencyData(
					Object.assign(
						{
							employeeId: this.employeeId,
							type: this.type,
						},
						obj,
					),
				);
				this.fetchTableDataByDate(Object.assign({ employeeId: this.employeeId }, obj));
			}
		},
		fetchTendencyData(obj) {
			tendencyData(obj).then((res) => {
				if (res.data && res.data.code === 0) {
					this.lineChartData = res.data.data;
					this.lineEchartsFn();
				}
			});
		},
		fetchTableDataByDate(obj) {
			let { current, size } = this.datePagination;
			let params = Object.assign(obj, {
				current,
				size,
			});
			tableDataByDate(params).then((res) => {
				if (res.data && res.data.code === 0) {
					let { records, current, size, pages, total } = res.data.data;
					this.dateTableData = records;
					this.datePagination = { current, size, pages, total };
				}
			});
		},
		sortDateTableData({ column, prop, order }) {
			let type = 1;
			switch (prop) {
				case 'synTime':
					type = 1;
					break;
				case 'chatCnts':
					type = 2;
					break;
				case 'messageCnts':
					type = 3;
					break;
				case 'replyPercentages':
					type = 4;
					break;
				case 'avgReplyTimes':
					type = 5;
			}
			let obj = {
				startTime: this.tendencyForm.startTime,
				endTime: this.tendencyForm.endTime,
				employeeId: this.employeeId,
				sort: order === 'ascending' ? 0 : 1,
				type,
			};
			this.fetchTableDataByDate(obj);
		},

		// 折线图配置
		lineEchartsFn() {
			let xAxisData = [];
			let seriesData = [];
			this.lineChartData.forEach((item) => {
				xAxisData.push(item.time);
				seriesData.push(item.number);
			});
			this.lineChartOption.xAxis.data = xAxisData;
			this.lineChartOption.series[0].data = seriesData;
			let unit = '',
				yAxisName = '';
			if (this.type === 1 || this.type === 2) {
				unit = '条';
				yAxisName = '条';
			} else if (this.type === 3) {
				unit = '%';
				yAxisName = '百分比(%)';
			} else {
				unit = '分钟';
				yAxisName = '分钟(min)';
			}
			this.lineChartOption.yAxis.name = yAxisName;
			this.lineChartOption.tooltip.formatter = `{b}<br>${this.typeName}: {c}${unit}`;

			let echarts = require('echarts');

			// 绘制图表
			this.$nextTick(() => {
				// 基于准备好的dom，初始化echarts实例
				let myChart = echarts.init(document.getElementById('detailLineChart'));
				myChart.setOption(this.lineChartOption);
			});
		},
		// 按日期查看 分页
		handleSizeChangeByDate(val) {
			this.datePagination.size = val;
			this.datePagination.current = 1;
			let obj = {
				startTime: this.tendencyForm.startTime,
				endTime: this.tendencyForm.endTime,
				employeeId: this.employeeId,
			};
			this.fetchTableDataByDate(obj);
		},
		handleCurrentChangeByDate(val) {
			this.datePagination.current = val;
			let obj = {
				startTime: this.tendencyForm.startTime,
				endTime: this.tendencyForm.endTime,
				employeeId: this.employeeId,
			};
			this.fetchTableDataByDate(obj);
		},

		// 拉取客户列表数据
		fetchCustomerData() {
			customerData({ employeeId: this.employeeId }).then((res) => {
				if (res.data && res.data.code === 0) {
					this.customerTableData = res.data.data;
				}
			});
		},
		// 跳转客户详情
		showDetail(contactId) {
			this.detailShow = true;
			this.detailMsg = {
				employeeId: this.employeeId,
				contactId,
			};
		},
		// 控制客户详情显示
		setDetailShow() {
			this.detailShow = false;
		},
	},
};
</script>
<style lang="scss" scoped>
.madp-go-back {
	background-color: #fff;
	padding: 8px 10px;
	line-height: 30px;
	font-size: 15px;
}
.madp-back-title {
	padding-top: 20px;
	margin: 0 auto;
	width: calc(100% - 60px);
	position: relative;
}
.madp-employee-info-wrap {
	display: flex;
	padding: 8px 10px;
	padding-top: 40px;
	.madp-employee-item {
		height: 118px;
		background: #fff;
		box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
		display: flex;
		-webkit-box-align: center;
		align-items: center;
		position: relative;
		margin-right: 20px;
		flex: 1;
		border-radius: 4px;
	}
	.madp-top-statistics-box.madp-employee-item {
		border: none;
	}
	.madp-employee-item:last-child {
		margin-right: 0;
	}
	.madp-employee {
		display: flex;
		align-items: center;
		padding: 24px 24px 25px;
		margin-top: 0;
		.madp-employee-avatar {
			width: 64px;
			height: 64px;
			border-radius: 4px;
			font-size: 22px;
			object-fit: contain;
			display: block;
			margin-right: 16px;
		}
		span.madp-employee-avatar {
			background-color: #ed5555;
			text-align: center;
			line-height: 64px;
			color: #fff;
		}
		.madp-employee-name {
			font-size: 18px;
			color: rgba(0, 0, 0, 0.85);
			line-height: 22px;
		}
		.madp-operation-tags {
			display: flex;
			align-items: center;
			.madp-operation-tag {
				border-radius: 3px;
				padding: 0 6px;
				height: 22px;
				line-height: 20px;
				display: inline-block;
				font-size: 12px;
				margin-right: 8px;
				background: #eff8ff;
				border: 1px solid #1890ff;
				color: #1890ff;
				margin-top: 10px;
			}
		}
	}
}
.madp-statistics-title {
	color: #333;
	font-weight: bold;
	font-size: 20px;
}
.madp-top-statistics-boxs {
	display: flex;
	align-items: center;
	margin-top: 20px;
}
.madp-top-statistics-box {
	width: 100%;
	height: 118px;
	background: #fbfdff;
	border: 1px solid #cfe8ff;
	display: flex;
	-webkit-box-align: center;
	align-items: center;
	position: relative;
	margin-right: 20px;
	.madp-divider {
		width: 1px;
		height: 50px;
		background-color: #f2f2f2;
	}
	.madp-statistics-item {
		width: 48%;
		display: flex;
		flex-direction: column;
		justify-content: center;
		align-items: center;
		font-weight: bold;
		font-size: 13px;
		color: #8691a4;
		.madp-statistics-item-number-wrap {
			font-weight: normal;
			.madp-statistics-item-number {
				font-size: 32px;
				color: #394457;
			}
		}
	}
}

.madp-horizontal-divider {
	width: 100%;
	height: 4px;
	margin: 20px 0;
	background-color: #f0f2f5;
}
.madp-gap-wrap {
	margin-top: 10px;
	.madp-data-tip {
		width: 100%;
		height: 18px;
		text-align: left;
		font-size: 13px;
		font-weight: 400;
		color: rgba(0, 0, 0, 0.45);
		margin: 16px 0 16px 8px;
	}
	.madp-statistics-table {
		margin-top: 20px;
	}
}
.madp-statistics-tabs {
	margin-top: 20px;
	display: flex;
	align-items: center;
	justify-content: space-between;
	.madp-chart-form .el-form-item {
		margin-right: 20px;
		margin-bottom: 0;
	}
	.madp-date-select {
		width: 120px;
	}
	.el-date-editor--daterange.el-input__inner {
		width: 300px;
	}
	/deep/ .el-date-editor .el-range-separator {
		width: 25px !important;
	}
}
.madp-table-user-wrap {
	display: flex;
	align-items: center;
	.madp-table-avatar {
		display: block;
		width: 32px;
		height: 32px;
		object-fit: contain;
		margin-right: 10px;
		border-radius: 4px;
	}
	span.madp-table-avatar {
		background-color: #ed5555;
		text-align: center;
		line-height: 32px;
		color: #fff;
	}
}
/deep/ .el-button--primary.is-plain {
	background-color: #fff;
	border-color: #ed5555;
}

.madp-customer-total {
	font-size: 14px;
	color: #333;
	margin-top: 10px;
}
.madp-black-pagination {
	display: flex;
	flex-direction: row;
	justify-content: flex-end;
	margin-top: 10px;
}
</style>
